<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\reportexcel;

use app\command\BaseWork;
use app\model\report\ReportRecordExcelModel;
use app\service\report\ReportRecordExcelService;
use app\service\report\ReportRecordListService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ReportRecordListWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('v3_report_record_list_work');
        $this->setDescription('生成报表发送记录数据');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('生成报表发送记录开始');
        $sendWeek = intval(date('w'));
        $sendDate = intval(date('Ymd'));
        $items = ReportRecordExcelService::getWeekList($sendWeek);
        if ($items) {
            foreach ($items as $obj) {
                if (! $obj instanceof ReportRecordExcelModel || ! $obj->getKey()) {
                    $this->getOutputMessage('报表暂无数据');
                    continue;
                }
                if ($obj->getAttr('is_send') == ReportRecordExcelModel::SEND_NO) {
                    $this->getOutputMessage('报表已关闭');
                    continue;
                }
                try {
                    $this->getOutputMessage('生成发送记录数据开始,报表id:' . $obj->getKey());
                    $res = ReportRecordListService::addData($obj, $sendDate);
                    if (! $res) {
                        $this->getOutputMessage('生成发送记录数据失败,报表id:' . $obj->getKey() . ReportRecordListService::getError(0));
                    } else {
                        $this->getOutputMessage('生成发送记录数据成功,报表id:' . $obj->getKey());
                    }
                } catch (\Exception $e) {
                    $this->getOutputMessage('生成发送记录数据失败' . $e->getMessage(0));
                }
            }
        } else {
            $this->getOutputMessage('暂无报表数据');
        }
        $this->getOutputMessage('生成发送记录数据结束');
    }
}
